#!/bin/bash

# 配置变量
RUN_NPM_OPEN_BUILD=false
PROJECT_DIR="/Users/chenamin/Documents/workspace/shanjie/backup/ebackup/open-eBackup/src/ProtectManager/component/PM_GUI/src/service/console"
REMOTE_SERVER="172.16.63.10"
REMOTE_USER="ibc_os_hs"
REMOTE_PASSWORD="Storage@21st"  # 注意：硬编码密码存在安全风险，建议使用SSH密钥
REMOTE_DIR="/home/ibc_os_hs"

# 进入项目目录
echo "进入项目目录: $PROJECT_DIR"
cd "$PROJECT_DIR" || {
    echo "无法进入项目目录，退出"
    exit 1
}

# 检查并删除dist目录（如果配置了执行构建）
if [ "$RUN_NPM_OPEN_BUILD" = "true" ]; then
    if [ -d "dist" ]; then
        echo "dist目录已存在，删除它"
        sudo rm -rf dist
    fi
fi

# 执行i18n检查
echo "执行npm run i18n"
npm run i18n

# 检查i18n结果文件
content=$(cat repeat-i18n.json | grep "}" | sed 's/{//g' | sed 's/}//g')
if [ -n "$content" ]; then
    echo "ERROR: repeat-i18n.json内容不为空"
    cat repeat-i18n.json
    exit 1
fi

# 执行构建命令（如果配置了执行）
if [ "$RUN_NPM_OPEN_BUILD" = "true" ]; then
    echo "执行npm run open-build"
    npm run open-build
else
    echo "跳过执行npm run open-build"
fi

# 重命名构建输出目录
if [ -d "dist/pm-gui" ]; then
    echo "将dist/pm-gui重命名为dist/console"
    sudo mv dist/pm-gui dist/console
else
    echo "WARNING: dist/pm-gui目录不存在，跳过重命名"
fi

# 压缩构建结果
if [ -d "dist/console" ]; then
    echo "压缩console目录为console.zip"
    cd dist || {
        echo "无法进入dist目录，退出"
        exit 1
    }
    sudo zip -r console.zip console/
    cd .. || exit
else
    echo "WARNING: dist/console目录不存在，跳过压缩"
fi

# 传输文件到远程服务器
if [ -f "dist/console.zip" ]; then
    echo "将console.zip传输到远程服务器$REMOTE_SERVER:$REMOTE_DIR/"
    sudo chown -R 15012:99 dist/console
    sshpass -p "$REMOTE_PASSWORD" scp dist/console.zip $REMOTE_USER@$REMOTE_SERVER:$REMOTE_DIR/
else
    echo "WARNING: console.zip文件不存在，跳过传输"
fi

# 在远程服务器上执行操作
sshpass -p "$REMOTE_PASSWORD" ssh -T $REMOTE_USER@$REMOTE_SERVER << 'ENDSSH'
REMOTE_DIR="/home/ibc_os_hs"

# 删除旧的console目录
if [ -d "$REMOTE_DIR/console" ]; then
    echo "删除远程服务器上的旧console目录"
    sudo rm -rf "$REMOTE_DIR/console"
fi

# 解压新的console.zip
if [ -f "$REMOTE_DIR/console.zip" ]; then
    echo "解压console.zip到$REMOTE_DIR/"
    sudo unzip "$REMOTE_DIR/console.zip" -d "$REMOTE_DIR/"
else
    echo "WARNING: 远程服务器上的console.zip文件不存在，跳过解压"
fi

# 拷贝到容器
CONTAINER_ID=$(sudo isula ps | grep k8s_pm-gui_protectmanager-biz-service | awk '{print $1}')
if [ -n "$CONTAINER_ID" ]; then
    echo "将新console目录拷贝到容器$CONTAINER_ID中"
    sudo chown -R 15012:99 "$REMOTE_DIR/console"
    sudo isula cp "$REMOTE_DIR/console/." $CONTAINER_ID:/app/gui/frontend/console/
else
    echo "WARNING: 未找到目标容器，跳过拷贝"
fi
ENDSSH

echo "所有操作完成"
